package com.e3.basdoc.corp.dao;

import java.util.List;

import com.e3.basdoc.corp.entity.CorpEntity;
import com.e3.basdoc.corp.model.CorpModel;
import com.e3.basdoc.corp.model.CorpQC;
import com.e3.core.base.SuperDAO;

public class CorpDAO extends SuperDAO {

	private String querySQL = "SELECT t FROM CorpEntity t";

	public List<CorpEntity> getCorpsByCondition(CorpQC CorpQC) {
		String sql = querySQL;
		CorpQC.setPrefix("t");
		String whereSQL = CorpQC.getWhereSQL();
		if (whereSQL != null && whereSQL.length() > 0) {
			sql = sql + " WHERE " + whereSQL;
		}
		return this.find(sql);
	}

	public void deleteCorpByCodes(List<CorpModel> corpModels) {
		if (corpModels == null || corpModels.isEmpty()) {
			return;
		}
		String[] codes = new String[corpModels.size()];
		for (int i = 0; i < corpModels.size(); i++) {
			codes[i] = corpModels.get(i).getCode();
		}
		this.deleteAllBySingleField(CorpEntity.class, "code", codes);
	}

	public void deleteCorpByIds(Long[] ids) {
		this.deleteAllBySingleField(CorpEntity.class, "id", ids);
	}

	public void deleteCorpChildren(Long[] parentIds) {
		if (parentIds == null || parentIds.length == 0) {
			return;
		}
		this.deleteAllBySingleField(CorpEntity.class, "parentId", parentIds);
	}

	public CorpEntity getCorpByCode(String code) {
		String whSql = " WHERE t.code = ?";
		String sql = querySQL + whSql;
		List<CorpEntity> entities = this.find(sql, code);
		return (entities == null || entities.size() == 0) ? null : entities.get(0);
	}
	
	public CorpEntity getSimpleCorpByCode(String code) {
		String whSql = "SELECT new CorpEntity(t.id,t.code,t.name,t.shortName) FROM CorpEntity t WHERE t.code = ?";
		String sql = querySQL + whSql;
		List<CorpEntity> entities = this.find(sql, code);
		return (entities == null || entities.size() == 0) ? null : entities.get(0);
	}

	public long childrenCount(long pId) {
		String sql = "SELECT count(t) FROM CorpEntity t WHERE t.parentId = ?";
		return this.counter(sql, pId);
	}

}
